<template>
	<el-form ref="ruleFormRef" label-position="top" :model="formInline" :rules="formRules" label-width="auto"
		v-loading="isLoading">
		<el-row :gutter="30">

			<re-col :value='24' :xs='24' :sm='24'>
				<el-form-item :label='titles?.SN' prop='SN'>
					<el-input v-model.trim='formInline.SN' :autosize="{ minRows: 4 }" type="textarea" clearable
						:disabled="formInline?.status == 1" placeholder='请输入设备序列号,多个使用","分开,例如:123,125,333'
						:formatter="(value) => value.replace(/[，]/g, ',')"
						:parser="(value) => value.replace(/[，]/g, ',')" />
				</el-form-item>
			</re-col>

			<re-col :value='24' :xs='24' :sm='24'>
				<el-form-item :label='titles?.modelInfo' prop='modelInfo'>
					<div class="w-full flex-bc gap-[10px]">
						<el-select v-model="formInline.factoryId" :placeholder="prompt.factoryId"
							:disabled="formInline?.status == 1" :style="{ width: '100%' }"
							@change="formInline.productId = null; formInline.modelId = null">
							<el-option v-for="item in factoryList" :key="item.value" :label="item.factoryName"
								:value="item.factoryId" />
						</el-select>
						<el-select v-model="formInline.productId" :placeholder="prompt.productId"
							:disabled="formInline?.status == 1" :style="{ width: '100%' }"
							@change="formInline.modelId = null">
							<el-option v-for="item in productList" :key="item.value" :label="item.productName"
								:value="item.productId" />
						</el-select>
						<el-select v-model="formInline.modelId" :placeholder="prompt.modelId"
							:disabled="formInline?.status == 1" :style="{ width: '100%' }">
							<el-option v-for="item in modelList" :key="item.value" :label="item.modelName"
								:value="item.modelId" />
						</el-select>
					</div>
				</el-form-item>
			</re-col>
			<re-col :value='12' :xs='24' :sm='24'>
				<el-form-item :label='titles?.unityId' prop='unityId'>
					<unitParentSelect v-model='formInline.unityId' clearable :style="{ width: '100%' }"
						:disabled="formInline?.status == 1" :placeholder='prompt?.unityId'
						@blur="formValidateField(ruleFormRef, 'unityId')" />
				</el-form-item>
			</re-col>
			<re-col :value='12' :xs='24' :sm='24'>
				<el-form-item :label='titles?.expireDate' prop='expireDate'>
					<el-date-picker :style="{ width: '100%' }" v-model="formInline.expireDate" clearable type="date"
						:disabled="formInline?.status == 1" :placeholder='prompt?.expireDate' format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" />
				</el-form-item>
			</re-col>
			<re-col :value='12' :xs='24' :sm='24'>
				<el-form-item :label='titles?.serveTime' prop='serveTime'>
					<el-input v-model.trim="formInline.serveTime" :placeholder='prompt?.serveTime'
						:disabled="formInline?.status == 1" :formatter="(value) => value.replace(/[^\d]/g, '')"
						:parser="(value) => value.replace(/[^\d]/g, '')">
						<template #append>月</template>
					</el-input>
					<div class="text-[#999999]">注：服务时长为个体用户激活序列号后的可使用时长。</div>
				</el-form-item>


			</re-col>
			<re-col :value='12' :xs='24' :sm='24'>
				<el-form-item :label='titles?.superviseUnityIds' prop='superviseUnityIds'>
					<superviseUnitySelect v-model='formInline.superviseUnityIds' clearable multiple
						:placeholder='prompt?.superviseUnityIds' :style="{ width: '100%' }"
						@blur="formValidateField(ruleFormRef, 'superviseUnityIds')" />
				</el-form-item>
			</re-col>
		</el-row>
	</el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import ReCol from "@/components/ReCol";
import type { FormRules } from "element-plus";
import { titles, prompt } from './index';
import type { infoType } from '@/api/manage/resource-management/serial-number-management/index';
import type { CascaderProps } from 'element-plus'
import { getProductTypeSelectList, getProductModelSelectList } from '@/api/manage/resource-management/serial-number-management/index';
import { getFactorySelectList } from '@/api/manage/product-management/product-type/index'
import superviseUnitySelect from '@/components/select/superviseUnitySelect/superviseUnitySelect.vue'
import unitParentSelect from '@/components/select/unitParentSelect/unitParentSelectTree.vue'
import { formValidateField } from '@/utils/functions'
import { message } from "@/utils/message";
type FormProps = {
	formInline: infoType,
	isLoading: boolean,
}

const props = withDefaults(defineProps<FormProps>(), {
	formInline: () => ({} as infoType),
	isLoading: false,
});

const formRules = reactive(<FormRules>{
	SN: [{ required: true, message: prompt?.SN, trigger: 'blur' },
	{
		validator: (rule, value, callback) => {
			if (!value) {
				callback(prompt?.SN);
			} else {
				value = value.replace(/,+/g, ',')
				if (value[value.length - 1] == ',') {
					value = value.substring(0, value.length - 1)
				}
				props.formInline.SN = value
				let arr = value.split(',').map(item => item.trim());
				let regex = /^[a-zA-Z0-9]{10,16}$/
				let arr1 = arr.filter((item, index) => {
					return arr.indexOf(item) !== index;
				});
				if (props.formInline.id && arr.length > 1) {
					callback(new Error('编辑时仅可输入一个序列号'));
				}
				if (arr.indexOf('') != -1) {
					callback(new Error('序列号不能为空'));
				} else if (arr1.length > 0) {
					callback(new Error('序列号不能重复'));
				} else if (arr.some(item => {
					if (!regex.test(item)) {
						message(`序列号 ${item} 格式错误！`, { type: 'error' });
						return true;
					} else {
						return false;
					}
				})) {
					callback(new Error('序列号为10-16位字母或数字组合'));
				} else {
					callback();
				}
			}
		}, trigger: 'blur'
	}],
	modelInfo: [{ required: true, message: prompt?.modelInfo, trigger: 'blur' },
	{
		validator: (rule, value, callback) => {
			if (!props.formInline.factoryId) {
				callback(new Error('请选择工厂'));
			} else if (!props.formInline.productId) {
				callback(new Error('请选择产品类型'));
			} else if (!props.formInline.modelId) {
				callback(new Error('请选择产品型号'));
			} else {
				callback();
			}
		}
	}],
	expireDate: [{ required: true, message: prompt?.expireDate, trigger: 'blur' },],
	unityId: [{ required: true, message: prompt?.unityId, trigger: 'blur' },],
	superviseUnityIds: [{ required: false, message: prompt?.superviseUnityIds, trigger: 'blur' },],
	serveTime: [{ required: false, message: prompt?.serveTime, trigger: 'blur' },],
});
const ruleFormRef = ref();
const factoryList = ref([])
const productList = ref([])
const modelList = ref([])
getFactorySelectList().then(res => {
	factoryList.value = res.result
})
watch(() => props.formInline.factoryId, () => {
	if (!props.formInline.factoryId) return;
	getProductTypeSelectList({ factoryId: props.formInline.factoryId }).then(res => {
		productList.value = res.result
	})
}, {
	immediate: true,
	deep: true
})
watch(() => props.formInline.productId, () => {
	if (!props.formInline.productId) return;
	getProductModelSelectList({ productId: props.formInline.productId }).then(res => {
		modelList.value = res.result
	})
}, {
	immediate: true,
	deep: true
})

const loadCascaderOptions = () => {

}

function getRef() {
	return ruleFormRef.value;
}

defineExpose({ getRef, loadCascaderOptions });
</script>
